# 使用cookie登录淘宝
import time
from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# 打开浏览器
service = Service(r"D:\app\Python38\chromedriver.exe")
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
# 创建浏览器对象
driver = webdriver.Chrome(options=chrome_options)

"""
需求：使用cookie实现跳过登录
1). 手动登录淘宝，获取cookie
2). 使用获取到的cookie，达到登录目的，然后就可以执行登录之后的操作
"""
# 1. 先访问淘宝页面，确保域名匹配（关键步骤）
driver.get("https://www.taobao.com")
# 等待页面加载
time.sleep(2)

# 2. Cookie字符串
cookie_str = "mtop_partitioned_detect=1; _m_h5_tk=fbaf04164a9199a47fef538b04237360_1762264812055; _m_h5_tk_enc=967608d84568377c69fcf9e3a9b6861d; cookie2=1fcec182588f053b9a4edfec47346fa8; t=66416446b5c41a3c830a49d68c540c02; _tb_token_=363a9536e7573; cna=xNGQIXM0D28BASQIhFmffY3V; thw=xx; sca=e5502240; arms_uid=891b1b35-e63f-4710-8bbb-ad2aa9e94031; xlly_s=1; _samesite_flag_=true; 3PcFlag=1762255865730; wk_cookie2=14d11d1ea7058e4c7dc20786ab5d6608; wk_unb=UUphzWIf%2BnfZ4H99FQ%3D%3D; sgcookie=E1006S3EfQfd%2BwejA%2Bs3stSvya9O5wWZ6Rz2S%2FiXy4MSUmWNAnqMurXrXsAG1JurYtx%2BUSMwG2jwUwjj2zcAvNOhSQFOrWSwgR3WokywXqb6E%2Fo%3D; _hvn_lgc_=0; havana_lgc2_0=eyJoaWQiOjIyMDc1NTg2MDEyODgsInNnIjoiODc1Njk2OWM4ZGExOTJiZjRmMjJkMmEwNzg5NThiMWMiLCJzaXRlIjowLCJ0b2tlbiI6IjFyMDNnSjBwWVZsMktmNzdzQnVvc2NRIn0; unb=2207558601288; csg=e330de17; lgc=tb798086052; cancelledSubSites=empty; cookie17=UUphzWIf%2BnfZ4H99FQ%3D%3D; dnk=tb798086052; skt=14a6322476b53f91; tracknick=tb798086052; _l_g_=Ug%3D%3D; sg=28b; _nk_=tb798086052; cookie1=WqOgn1%2F58EDcmQ5gH3PsetEBO1e2qd7JruS7mhghBrk%3D; uc1=cookie16=URm48syIJ1yk0MX2J7mAAEhTuw%3D%3D&cookie21=URm48syIYn73&cookie15=W5iHLLyFOGW7aA%3D%3D&cookie14=UoYY4dvcR8yLJQ%3D%3D&pas=0&existShop=false; sn=; uc3=vt3=F8dD2kv%2F1g27SJHfElM%3D&lg2=VFC%2FuZ9ayeYq2g%3D%3D&nk2=F5RCbIQU3OeoG4w%3D&id2=UUphzWIf%2BnfZ4H99FQ%3D%3D; existShop=MTc2MjI1NTkyOA%3D%3D; uc4=nk4=0%40FY4JgmL3PciYNFXSdR9NCwLsZ948Ag%3D%3D&id4=0%40U2grFn0sXWEFPXxlyB5nNX3OpaV6mnlL; _cc_=WqG3DMC9EA%3D%3D; aui=2207558601288; havana_lgc_exp=1793359931569; sdkSilent=1762284731569; havana_sdkSilent=1762284731569; isg=BE5OFjCmq7CxJB-US8GDMOK1nyQQzxLJyDG1rniVGdET2-k14F782X_ZEga3awrh; tfstk=gBIrdZG5TuEziblbVsKEQeF4Ni-J5HPsaMOBK9XHFQAoV0GhuOCeNJUJVZRFisRlT9eJKBfhTB_7ll6ReHK31Br_fT3rnCdAaBYknJvBpY2Xr5eCDRx315ZslxY8NHX5U-Iknqv9iLmkxU22mdvyKHYHEt22KpGo-0fhn-RvdpckxpAmnpJorHxhtt22pIAHxUfhn-JpiBc4oBAs0d8uhdZfvsiTXFdGEIonjA9yrXBqRcnO0L8PItd2FLs2UURw8CAK6gffKgsJkzukvt_NTwfgG4Ol7d525aPZ415JK9JhalHwigWF0UQjZ4vw4Q8GqFqUBt8hui-5qW3OhtRk7n_bk7TB4_796U4YM6W2N6jyobPXON6fqE5gGm5p8wjWmgV0bg8j9KYs--Vst28kHKR_3-mAQ_pcr_uQv23pyZp218e-J2LkHKR_3-uKJUKv3Cw8e"

# 3. 拆分Cookie字符串为独立键值对，逐个添加
for cookie_item in cookie_str.split('; '):
    # 分割key和value（处理value中可能包含=的情况）
    if '=' in cookie_item:
        key, value = cookie_item.split('=', 1)
        # 构造单个Cookie字典
        single_cookie = {
            'name': key,
            'value': value,
            'domain': '.taobao.com',  # 淘宝的Cookie通用域名
            'path': '/',
            'httpOnly': False,  # 适配于大部分淘宝Cookie
            'secure': False     # 非HTTPS环境也能生效
        }
        try:
            driver.add_cookie(single_cookie)
            print(f"添加成功Cookie: {key}")
        except Exception as e:
            # 部分Cookie可能因格式限制添加失败，不影响整体使用
            print(f"跳过的Cookie {key}: {str(e)[:50]}")

# 4. 刷新页面使Cookie生效
time.sleep(3)
driver.refresh()

time.sleep(3)
# 5. 退出浏览器
driver.quit()
